<template>
  <el-dialog
    :visible="visible"
    @update:visible="val => emit('update:visible', val)"
    @opened="initMap"
    @close="onDialogClose"
    title="确认打卡位置"
    width="400px"
  >
    <el-button size="small" @click="locateMe" style="margin-bottom: 10px;">我的位置</el-button>
    <div :id="mapId" style="width:100%;height:300px;"></div>
    <div style="margin:10px 0;">当前位置：{{ address }}</div>
    <template #footer>
      <el-button @click="onCancel">取消</el-button>
      <el-button type="primary" @click="onConfirm">确认打卡</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref } from 'vue'
const props = defineProps({
  visible: Boolean,
  latitude: Number,
  longitude: Number,
  mapId: {
    type: String,
    default: 'map'
  }
})
const emit = defineEmits(['update:visible', 'confirm', 'cancel'])

const address = ref('')
let map, marker

const getAddressFromCoords = (lng, lat) => {
  if (!window.AMap) {
    address.value = '无法获取地址';
    return;
  }
  
  // 添加错误处理和重试机制
  try {
    window.AMap.plugin('AMap.Geocoder', function () {
      const geocoder = new window.AMap.Geocoder({
        radius: 1000, // 搜索半径
        extensions: 'all' // 返回详细信息
      });
      
      geocoder.getAddress([lng, lat], function (status, result) {
        console.log('逆地理编码结果', status, result);
        if (status === 'complete' && result.regeocode) {
          address.value = result.regeocode.formattedAddress;
        } else {
          console.error('地理编码失败:', status, result);
          address.value = '无法获取地址';
        }
      });
    });
  } catch (error) {
    console.error('地理编码插件加载失败:', error);
    address.value = '地址解析失败';
  }
};

const initMap = () => {
  if (!window.AMap) {
    address.value = '地图API未加载';
    return;
  }
  
  try {
    // 清理之前的地图实例
    if (map) {
      map.destroy();
    }
    
    map = new window.AMap.Map(props.mapId, {
      center: [props.longitude, props.latitude],
      zoom: 16,
      viewMode: '2D',
      mapStyle: 'amap://styles/normal'
    });
    
    marker = new window.AMap.Marker({
      position: [props.longitude, props.latitude],
      map: map, // 直接指定map
      draggable: true,
      cursor: 'move',
      raiseOnDrag: true,
      offset: new window.AMap.Pixel(-10, -20)
    });
    marker.setDraggable(true);
    
    getAddressFromCoords(props.longitude, props.latitude);
    
    marker.on('dragend', (e) => {
      marker.setPosition([e.lnglat.lng, e.lnglat.lat]);
      getAddressFromCoords(e.lnglat.lng, e.lnglat.lat);
    });
    
  } catch (error) {
    console.error('地图初始化失败:', error);
    address.value = '地图加载失败';
  }
};

const locateMe = () => {
  if (!navigator.geolocation) {
    address.value = '浏览器不支持定位';
    return;
  }
  address.value = '正在定位...';
  navigator.geolocation.getCurrentPosition(
    (pos) => {
      const lat = pos.coords.latitude;
      const lng = pos.coords.longitude;
      // 移动地图和标记
      if (map && marker) {
        map.setCenter([lng, lat]);
        marker.setPosition([lng, lat]);
        getAddressFromCoords(lng, lat);
      }
    },
    (err) => {
      address.value = '定位失败，请检查浏览器权限';
    },
    {
      enableHighAccuracy: true,
      timeout: 10000,
      maximumAge: 0
    }
  );
};

const onCancel = () => {
  emit('update:visible', false)
  emit('cancel')
}
const onDialogClose = () => {
  // 清理地图实例
  if (map) {
    try {
      map.destroy();
      map = null;
    } catch (error) {
      console.error('地图销毁失败:', error);
    }
  }
  emit('cancel')
}
const onConfirm = () => {
  const lnglat = marker.getPosition()
  emit('confirm', {
    latitude: lnglat.lat,
    longitude: lnglat.lng,
    address: address.value
  })
  emit('update:visible', false)
}
</script>